package com.topvision.face;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class VideoCache {
	private static VideoCache cache = null;
	private static Object obj = new Object();
	private static AssetManager asst = null;
	private Set<String> fdSet = new HashSet<String>();
	
	
	private VideoCache(){}
	
	public static void setAssetManager(AssetManager _asst){
		asst = _asst;
	}
	
	public static AssetManager getAssetManager(){
		return asst;
	}
	
	public static VideoCache getInstance(){
		if(null==cache){
			synchronized (obj) {
				if(null==cache){
					cache = new VideoCache();
					cache.init();
				}
			}
		}
		
		return cache;
	}
	
	public boolean isResExists(String url){
		boolean exists = false;
		int index = url.lastIndexOf("/");
		String key = null;
		if(index!=-1){
			key = url.substring(index+1);
			exists = fdSet.contains(key);
		}
		Log.d("videoCache", "Url: " + url + " => " + key  + " = " + exists);
		
		return exists;
	}
	
	private void init(){
		try {
			//读取assest/video/下的所有文件
			String[] pathArr = asst.list("");
			for(String path : pathArr){
				if(path.equals("fbb.mp4")){
					AssetFileDescriptor ad = asst.openFd(path);
					fdSet.add(path);
				}
			
				Log.i("cache", "cached file : " + path);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
